package pay

import (
	"OnlineRetailers/controllers/OpenId"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type CheckPay struct {
	beego.Controller
}

func (c *CheckPay) CheckPay() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/pay/CheckPay"
	var err error
	//res:= &PAY.GetPay{}
	order := &User.Order{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	o := orm.NewOrm()

	id := c.GetString("id")

	//id="4200001200202109205740387428"
	openidTemp := c.Ctx.Request.Header["Openid"]

	if len(openidTemp) == 0 {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("openidNull"), addr, "openidNull")
		return
	}
	openid := openidTemp[0]
	if openid == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("openidNull"), addr, "openidNull")
		return
	}

	err = OpenId.CheckOpenId(openid)
	//fmt.Println(ses.Admin)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//err,resp:=findPay(id)
	//if err!=nil{
	//	c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
	//
	//	err=Destroy(id)
	//	if err!=nil{
	//		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
	//		return
	//	}
	//	return
	//}

	//
	//fmt.Println(resp.Amount.Total)
	//fmt.Println(core.Int64(int64(0.2*100)))

	//fmt.Println(*resp.OutTradeNo)
	fmt.Println(id)
	order, err = Find(id)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	//if int64(0.2*100)!=*(resp.Amount.Total){
	//	c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("金额不符合"), addr, "金额不符合")
	//	return
	//}

	fmt.Println(order)
	_, err = o.Insert(order)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}

func UsedCoupon(CouponId, openid string) (err error) {

	o := orm.NewOrm()
	sql := "update `w_x_user_coupons` set `used`=1 where `w_x_user_id`=? and `coupon_id`=?"
	Exc, err := o.Raw(sql, openid, CouponId).Exec()
	if err != nil {
		return
	}
	num, err := Exc.RowsAffected()
	if err != nil {
		return
	} else if num == 0 {
		err = fmt.Errorf("num == 0")
		return
	}
	return nil
}
